package com.clanmy.ui;

import com.clanmy.ui.controller.AnchorPaneController;
import com.fx.spring.annotation.StartFX;
import com.fx.spring.jfx.AbstractSpringStartFX;
import com.fx.spring.util.SpringContextUtil;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


@StartFX
public class ApplicationStartDemo extends AbstractSpringStartFX {

   /* @Autowired
    private AnchorPaneController anchorPaneController;*/


    @Override
    protected void start(Stage primaryStage) {

        Button fxmlLoaderButton = new Button("加载FXML");
        Button getSpringBean = new Button("获取SpringContextBean");


        HBox hBox = new HBox(10, fxmlLoaderButton, getSpringBean);
        hBox.setAlignment(Pos.CENTER);


        VBox vBox = new VBox(5);
        vBox.setAlignment(Pos.TOP_CENTER);

        ObservableList<Node> children = vBox.getChildren();
        children.add(hBox);

        Scene scene = new Scene(vBox, 800, 500);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ApplicationStartDemo");
        primaryStage.show();

        AtomicInteger count = new AtomicInteger();

        fxmlLoaderButton.setOnAction(event -> {
            // 测试多例模式 （需要把当前的 controller 设置回 FXMLLoader中）
            AnchorPaneController anchorPaneController = SpringContextUtil.getBean(AnchorPaneController.class);
            StackPane stackPane = anchorPaneController.load(anchorPaneController);

            if (!children.contains(stackPane)) {
                count.getAndIncrement();
                anchorPaneController.setTestLabelMessage("FXML文件"+count);
                children.add(stackPane);
                System.err.println(anchorPaneController);
                System.err.println(java.util.Optional.ofNullable(anchorPaneController.getLoader().getController()));
            }

        });


        getSpringBean.setOnAction(event -> {
            Map<String, Object> withAnnotationBeans = SpringContextUtil.getBeansWithAnnotation(Component.class);
            withAnnotationBeans.forEach((k, v) -> {
                System.out.println(k + " === " + v);
            });


        });

    }
}
